package daikoku;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import daikoku.utils.DatabaseUtils;

public class AnaliseAtraso {
	public static void main(String[] args) {
		Map<Integer, Integer> p = new TreeMap<Integer, Integer>();
		for (int i = 1; i <= 60; i++) {
			p.put(i, 0);
		}

		BufferedReader br = null;
		try {

			br = new BufferedReader(new FileReader(new File("docs/sena.csv")));
			String line = null;

			StringBuilder sb = new StringBuilder();
			for (int i = 1; i <= 60; i++) {
				sb.append("," + i);
			}
			System.out.println(sb.toString().substring(1));

			List<String> atrasos = new ArrayList<String>();

			while ((line = br.readLine()) != null) {
				Integer[] p1 = StringUtils.splitAsIntArray(line);

				for (int i = 1; i <= 60; i++) {
					p.put(Integer.valueOf(i), p.get(Integer.valueOf(i)) + 1);
				}

				for (int i = 0; i < p1.length; i++) {
					p.put(p1[i], 0);
				}

				sb = new StringBuilder();
				for (Integer key : p.keySet()) {
					sb.append("," + p.get(key));
				}

				atrasos.add(sb.toString().substring(1));
			}

			load(atrasos);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private static void load(List<String> atrasos) {
		// Load the application context
		ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
		DataSource ds = (DataSource) context.getBean("dataSource");

		String sql = "INSERT INTO TB_MS_ATRASOS (nu_sorteio, nu_dezena, qt_atraso) VALUES(?,?,?)";

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn = ds.getConnection();
			conn.setAutoCommit(false);

			pstmt = conn.prepareStatement(sql);

			int count = 0;

			for (String atraso : atrasos) {
				++count;

				Integer[] p = StringUtils.splitAsIntArray(atraso, false);
				for (int i = 0; i < p.length; i++) {
					pstmt.setInt(1, count);
					pstmt.setInt(2, i + 1);
					pstmt.setInt(3, p[i]);

					pstmt.addBatch();
				}

				if (count % 10 == 0) {
					pstmt.executeBatch();
					conn.commit();
					System.out.println(count);
				}
			}

			pstmt.executeBatch();
			conn.commit();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DatabaseUtils.close(conn, pstmt, rs);
		}
	}
}
